package com.myplans.server.util.converter;

import java.lang.reflect.InvocationTargetException;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.ConversionException;
import org.apache.commons.beanutils.Converter;
import org.apache.log4j.Logger;

import com.myplans.shared.User;
import com.myplans.vo.UserValue;


public class UserConverter implements Converter {

	private static Logger logger = Logger.getLogger(UserConverter.class);

	@SuppressWarnings("rawtypes")
	@Override
	public Object convert(Class type, Object value) throws ConversionException {

		if (value instanceof User) {
			UserValue operationalUserValue = new UserValue();
			try {
				BeanUtils.copyProperties(operationalUserValue, value);
			} catch (IllegalAccessException e) {
				logger.error("Failed to copy the bean's properties: " + e.getMessage());
				e.printStackTrace();
			} catch (InvocationTargetException e) {
				logger.error("Failed to copy the bean's properties: " + e.getMessage());
				e.printStackTrace();
			}
			return operationalUserValue;
		} else if (value instanceof UserValue) {
			User user = new User();
			try {
				BeanUtils.copyProperties(user, value);
			} catch (IllegalAccessException e) {
				logger.error("Failed to copy the bean's properties: " + e.getMessage());
				e.printStackTrace();
			} catch (InvocationTargetException e) {
				logger.error("Failed to copy the bean's properties: " + e.getMessage());
				e.printStackTrace();
			}
			return user;
		}

		logger.debug("Returning a null value, possibly a conversion error.");
		return null;
	}
}
